/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
var merge = function(intervals) {
  intervals = intervals.sort((a, b) => {
    if(a[0] == b[0]) {
      a[1] - b[1];
    } else {
      return a[0] - b[0];
    }
  });
  let temp = intervals[0], result = [];
  for(let i = 1; i < intervals.length; i++) {
    if(temp[1] >= intervals[i][0]) {
      if(intervals[i][1] >= temp[1])
        temp[1] = intervals[i][1];
    } else {
      result.push([...temp]);
      temp = intervals[i];
    }
  }
  result.push([...temp]);
  return result;
};
let intervals = [[1,3],[2,6],[8,10],[15,18]];
console.log(merge(intervals));
intervals = [[1,4],[4,5]];
console.log(merge(intervals));
intervals = [[1,4],[0,4]];
console.log(merge(intervals));
intervals = [[1,4],[1,4]];
console.log(merge(intervals));
intervals = [[1,4],[2,3]];
console.log(merge(intervals));
